import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author AMPM
 */

public class SaraClientHandler implements Runnable {
	private Socket socket;
	private HashMap<String, String> keyMap = new HashMap<String, String>();

	public SaraClientHandler(Socket socket) {
		this.socket = socket;

		// the private keys of A and B are added to Sara's keyMap
		keyMap.put("A", "aaaaaaaa");
		keyMap.put("B", "bbbbbbbb");
	}

	public void run() {
		try {

			// get the input and output stream from the socket
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();

			// wrap them in the ObjectInputStream and ObjectOutputStream objects

			ObjectInputStream ois = new ObjectInputStream(is);

			// get the data transmitted from the client
			ObjectOutputStream oos = null;

			long nonce = (Long) ois.readObject();
			String sender = (String) ois.readObject();
			String receiver = (String) ois.readObject();

			oos = SymmetricCrypt.encrypt(os, keyMap.get(sender));

			oos.writeObject(nonce);

			oos.flush();
			
			// create and write ticket to stream
			String key = createKey();
			String ticket = createTicket(sender, key);

			oos.writeObject(key);

			oos.writeObject(SymmetricCrypt.EncryptString(ticket,
					keyMap.get(receiver)));

			System.out.println(nonce);
			System.out.println(sender);
			System.out.println(receiver);

			oos.flush();
			oos.close();
			socket.close();
		} catch (IOException ignore) {
			System.out.println(ignore);
		} catch (ClassNotFoundException ignore) {
			System.out.println(ignore);
		} catch (Exception ignore) {
			System.out.println(ignore);
		}
	}

	private String createTicket(String sender, String key) {
		return sender + " " + key;
	}

	private String createKey() {
		String key = Integer.toString((int) (Math.random() * 600000000));
		return key.substring(0, 8);
	}
}
